<script setup lang="ts" name="enclosure_index">
import {
  getCurrentInstance,
  defineComponent,
  onMounted,
  onActivated,
  reactive,
  ref,
  toRaw,
} from "vue";
import {
  getCameraList_,
  getAllCameraList_,
  getFullDeptTree_,
  getUserVideoUrl,
} from "@/api/server_video";
import {
  getDeptTree,
  deviceSave,
  downloadQRCode,
  deviceDel,
} from "@/api/server_set_patrol";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { setAutoCheckALert, setAutoCheckData } from "@/utils/autoCheck";
import { deviceCount, detectionLog, deviceLog } from "@/api/server_repair";
import { deviceList } from "@/api/server_set_patrol";
import { getCameraVideoUrl } from "@/api/server_video";
import Bus from "@/utils/eventBus";
import * as echarts from 'echarts';
import { auto } from "@popperjs/core";
import airtrend from "./airtrend/airtrend.vue";
import { CirclePlus, Search, Refresh, EditPen, Share, Notebook, Setting } from '@element-plus/icons-vue'
import { url } from "inspector";
import { ElTable } from 'element-plus'

const router = useRouter();
const cameraList = ref<any[]>([]);
const isBig = ref(false);
const go = () => {
  router.push({ name: "page2", params: { a: 1 } });
};
const height = ref(0);
const pageSize = ref(20);
const isEdit = ref(false);
const tempIndex = ref();
const dialogVisible_add = ref(false);
const dialogVisible_map = ref(false);
const fileList = ref<any[]>([]);
const baseURL = import.meta.env.VITE_RES_URL + '/admin/config/uploadFile';
const formData = ref<any>({
  dept_type:'',
  coordinate:'',
});
const deviceStatusOption = ref<any>({});
const deeptTypeOption = ref<any>({});
const deptOptions = ref([]);
const total = ref(0);
const List = ref([]);
const showDrawer = ref(false);
const showFileDrawer = ref(false);
const deviceLogList = ref<any[]>([]);
const deviceLogTotal = ref(0);
const device_id = ref();
const currentPage = ref(1);
const deviceLogForm = ref({
  page: 1,
  pageSize: 20,
});
const cascaderProps = reactive({
  label: 'label',
  value: 'id',
  children: 'children',
  checkStrictly:true,
  emitPath:false,
})

// 选择器
const options = [
  {
    value: 'guide',
    label: '1号楼',
  },
  {
    value: 'guide',
    label: '2号楼',
  },
  {
    value: 'guide',
    label: '3号楼',
  },
  {
    value: 'guide',
    label: '4号楼',
  },
  {
    value: 'guide',
    label: '5号楼',
  },
]
const options1 = [
  {
    value: 'guide',
    label: '1F',
  },
  {
    value: 'guide',
    label: '2F',
  },
  {
    value: 'guide',
    label: '3F',
  },
  {
    value: 'guide',
    label: '4F',
  },
  {
    value: 'guide',
    label: '5F',
  },
]


const phonehandleClose = (done: () => void) => {
  ElMessageBox.confirm("Are you sure to close this dialog?")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};

const getAllCameraList = async () => {
  let res = await deviceList({});
  if (res.result == "success") cameraList.value = res.list;
};

const returnCameraIndex = (data: any) => {
  if (!data) {
    return;
  }
  let coordinate = data.coordinate || "";
  let left = coordinate.split(",")[0];
  let top = coordinate.split(",")[1];
  return { top: `${top}px`, left: `${left}px` };
};

const doubleclick = (event: any) => {
  isBig.value = !isBig.value;
  if (!isBig.value) {
    setMap();
    return;
  }
  let offsetX = event.offsetX;
  let offsetY = event.offsetY;
  let mapBlock: any = document.querySelector(".map-block");
  let mapId: any = document.querySelector(".map-id");
  let mapBlockHeight = mapBlock.clientHeight;
  let mapBlockWidth = mapBlock.clientWidth;
  let mapIdHeight = mapId.clientHeight;
  let mapIdWidth = mapId.clientWidth;
  let left = -event.offsetX + mapBlockWidth / 2;
  let top = -event.offsetY + mapBlockHeight / 2;
  setTimeout(() => {
    if (left > 0) left = 0;
    if (left < mapBlockWidth - mapIdWidth) left = mapBlockWidth - mapIdWidth;
    if (top > 0) top = 0;
    if (top < mapBlockHeight - mapIdHeight) top = mapBlockHeight - mapIdHeight;
    mapId.style.transform = `scale(${1})`;
    mapId.style.left = `${left}px`;
    mapId.style.top = `${top}px`;
  }, 100);
  mapId.oncontextmenu = function () {
    return false;
  };

  mapId.addEventListener("mousedown", function (event: any) {
    event.stopPropagation();
    var code = event.which;
    if (code != 3 || !isBig.value) {
      return;
    }
    let left = parseInt(mapId.style.left);
    let top = parseInt(mapId.style.top);
    let ol = event.clientX;
    let ot = event.clientY;
    document.onmousemove = function (ev) {
      let l = left + ev.clientX - ol;
      let t = top + ev.clientY - ot;
      if (l > 0) l = 0;
      if (l < mapBlockWidth - mapIdWidth) l = mapBlockWidth - mapIdWidth;
      if (t > 0) t = 0;
      if (t < mapBlockHeight - mapIdHeight) t = mapBlockHeight - mapIdHeight;
      mapId.style.left = l + "px";
      mapId.style.top = t + "px";
    };
    document.onmouseup = function () {
      document.onmousemove = null;
    };
  });
};

const setMap = () => {
  let mapBlock: any = document.querySelector(".map-block");
  let mapId: any = document.querySelector(".map-id");
  mapId.style.opacity = 1;
  let mapBlockHeight = mapBlock.clientHeight;
  let mapBlockWidth = mapBlock.clientWidth;
  let mapIdHeight = mapId.clientHeight;
  let mapIdWidth = mapId.clientWidth;
  let zoomVal = mapBlockHeight / mapIdHeight;
  let left = (mapBlockWidth - mapIdWidth) / 2;
  let top = (mapBlockHeight - mapIdHeight) / 2;
  mapId.style.transform = `scale(${zoomVal})`;
  mapId.style.left = `${left}px`;
  mapId.style.top = `${top}px`;
  mapId.oncontextmenu = function () {
    return false;
  };
};

const cameraClick = async (data: any) => {
  let res = await getCameraVideoUrl({
    id: data.camera_id,
  });
  if (res.result == "success") {
    Bus.$emit("openVideo", res);
  }
};

onMounted(() => {
  getList(0);
  getDeptInfo();
  getAllCameraList();
  setTimeout(() => {
    setMap();
  }, 500);
});


//添加设备



const addItem = () => {
  isEdit.value = false;
  formData.value = {
    dept_type: "inner",
  };
  fileList.value = [];
  dialogVisible_add.value = true;
};
const openMap = ()=> {
  dialogVisible_map.value = true;
  setTimeout(() => {
      setMop()
  },100)
}

const doublelick = (event: any)=>{
      isBig.value = !isBig.value;
      if(!isBig.value){
          setMop()
          return
      }
      let ffsetX = event.offsetX
      let ffsetY = event.offsetY
      let mopBlock:any = document.querySelector('.setMapBlock-body')
      let mopId:any = document.querySelector('.setMapBlock')
      let mopBlockHeight = mopBlock.clientHeight
      let mopBlockWidth = mopBlock.clientWidth
      let mopIdHeight = mopId.clientHeight
      let mopIdWidth = mopId.clientWidth
      let left = - event.offsetX + mopBlockWidth/2
      let top = - event.offsetY + mopBlockHeight/2
      setTimeout(() => {
          if(left>0)  left = 0
          if(left< mopBlockWidth-mopIdWidth)  left =  mopBlockWidth-mopIdWidth
          if(top>0)  top = 0
          if(top< mopBlockHeight-mopIdHeight)  top = mopBlockHeight-mopIdHeight
          mopId.style.transform = `scale(${1})`
          mopId.style.left = `${left}px`
          mopId.style.top = `${top}px`
      },100)
      mopId.oncontextmenu = function () {
          return false;
      }

      mopId.addEventListener("mousedown", function(event: any){

          event.stopPropagation();
          var code = event.which;
          if(code != 3  || !isBig.value){
              return
          }
          let left = parseInt(mopId.style.left)
          let top = parseInt(mopId.style.top)
          let ol = event.clientX
          let ot = event.clientY
          document.onmousemove = function(ev){
              let l = left + ev.clientX - ol
              let t =  top + ev.clientY - ot
              if(l>0)  l = 0
              if(l< mopBlockWidth-mopIdWidth)  l = mopBlockWidth-mopIdWidth
              if(t>0)  t = 0
              if(t< mopBlockHeight-mopIdHeight)  t =mopBlockHeight-mopIdHeight
              mopId.style.left =  l + "px";
              mopId.style.top = t + "px";
          }
          document.onmouseup = function(){
              document.onmousemove = null;
          }

      })
  }
const setMop = ()=> {
  let mopBlock:any = document.querySelector('.setMapBlock-body')
  let mopId:any = document.querySelector('.setMapBlock')
  let mopBlockHeight = mopBlock.clientHeight
  let mopBlockWidth = mopBlock.clientWidth
  let mopIdHeight = mopId.clientHeight
  let mopIdWidth = mopId.clientWidth
  let zomVal = mopBlockHeight / mopIdHeight;
  let left = (mopBlockWidth - mopIdWidth) / 2
  let top = (mopBlockHeight - mopIdHeight) / 2
  mopId.style.transform = `scale(${zomVal})`
  mopId.style.left = `${left}px`
  mopId.style.top = `${top}px`
  mopId.oncontextmenu = function () {
      return false;
  }
}

const mapClick = (event: any)=>{
    let ffsetX = event.offsetX
    let ffsetY = event.offsetY
    function setMapndex(x:number, y:number) {
        let indePoint:any = document.querySelector('.index-point')
        indePoint.style.top = `${y}px`
        indePoint.style.left = `${x}px`
        indePoint.style.display = `block`
        tempIndex.value = `${x},${y}`
    }
    setMapndex(ffsetX,ffsetY)
}

const setIndex = ()=>{
   formData.value.coordinate = tempIndex.value
   dialogVisible_map.value = false;
}

const confirmAdd = async (val: number) => {
  //保存数据
  let files = fileList.value.map(v=>{
    if(v.url){
      return v.url
    }
  })
  console.log(formData.device_id)
  let res = await deviceSave({
    ...formData.value,
    id: isEdit.value ? formData.value.device_id : 0,
    deptId:formData.value.dept_id,
    deptType:formData.value.dept_type,
    deptMark:formData.value.dept_mark,
    factoryPhone:formData.value.factory_phone,
    files:files.join(',')
  })
  if(res.result === 'success'){
     ElMessage({
        type: "success",
        message: "保存成功!",
      });
    dialogVisible_add.value = false
      //添加完成后重新获取数据
    getList(0)
  }
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getList(currentPage.value);
};
const handleCurrentChange = (val: number) => {
  getList(val);
};
const handleCurrentChange2 = (val: number) => {
  deviceLogForm.value.page = val;
  getDeviceLog();
};
const handlePreview = (file: any) => {
   window.open(file.url)
};
const handleRemove = (file: any, fileList: any) => {
   fileList.value = fileList
};
const handleAvatarSuccess = (res: any, file: any, fileList: any) => {
  file.url = res.fileUrl
  fileList.value = fileList
};

const getList = async (page: number) => {
  let res = await deviceList({
    page: page || 1,
    pageSize: pageSize.value,
  });
  console.log(res)
  if (res.result == "success") {
    List.value = res.list;
    deviceStatusOption.value = res.deviceStatusOption;
    deeptTypeOption.value = res.deptTypeOption;
    total.value = Number(res.total);
  }
};
const getDeptInfo = async () => {
  let res = await getDeptTree({});
  if (res.result == "success") {
    deptOptions.value = res.deptTree;
  }
};

const record = (data: any) => {
  showDrawer.value = true;
  device_id.value = data.device_id;
  getDeviceLog();
};
const getDeviceLog = async () => {
  let res = await deviceLog({
    id: device_id.value,
    ...deviceLogForm.value,
  });
  if (res.result == "success") {
    deviceLogList.value = res.list;
    deviceLogTotal.value = Number(res.total);
  }
};

</script>

<template>
  <div class="enclosure-box">
    <div class="enclosure-top">
       <el-row>
        <el-col :span="5">
          <span>选择楼栋：</span><el-cascader :options="options" clearable />
        </el-col>
        <el-col :span="1">
        </el-col>
        <el-col :span="5">
          <span>选择楼层：</span><el-cascader :options="options1" clearable />
        </el-col>
        <el-col :span="5">
          <el-button type="primary" plain @click="addItem"> 添加设备</el-button>
        </el-col>
        <el-col :span="8" class="enclosure-img">
          正常<img src="@/assets/image/home/png/lan.png" alt="">
          离线<img src="@/assets/image/home/png/hui.png" alt="">
          报警<img src="@/assets/image/home/png/hong.png" alt="">
        </el-col>
      </el-row>
    </div>
    <div class="enclosure-bottom">
      <div class="visual-left">
      <div class="map-block">
        <div class="map-loading">地图加载中...</div>
        <div class="map-id" style="opacity: 0" @dblclick="doubleclick">
          <img class="map-image" src="@/assets/image/home/map.png" alt="" />
          <div class="index-point" :key="index" v-for="(c, index) in cameraList" :title="c.spec" @click="cameraClick(c)"
            :style="returnCameraIndex(c)">
            <!--  <img src="../image/gif/index2.gif"> -->
            <div class="camera-hover">
              <img src="@/assets/image/home/shebei1.png" />
              <img class="hover" src="@/assets/image/home/shebei2.png" />
            </div>
          </div>
          <!-- <div
              class="index-point"
              v-for="(c, index) in ngListCarmeta"
              @click="cameraClickNgList(c, index)"
              :style="returnCameraIndex(c.cameraInfo)"
            >
              <img src="../image/gif/index2.gif" />
            </div> -->
        </div>
      </div>
    </div>
    </div>
  </div>

  <el-dialog :close-on-click-modal="false"  :title="isEdit?'编辑设备':'新增设备'" v-model="dialogVisible_add" width="500px">
    <el-form ref="form" :model="formData" label-width="120px">
      <el-form-item label="设备编号" v-if="isEdit">
        <el-input type="number" disabled placeholder="请输入" v-model="formData.device_id"></el-input>
      </el-form-item>
      <el-form-item label="品牌名字">
        <el-input type="text" placeholder="请输入" v-model="formData.brand"></el-input>
      </el-form-item>
      <el-form-item label="型号">
        <el-input type="text" placeholder="请输入" v-model="formData.spec"></el-input>
      </el-form-item>
      <el-form-item label="地图坐标" >
              <div class="btn-act">
               <el-input class="btn-input" type="text" placeholder="坐标" disabled
                          v-model="formData.coordinate"></el-input>
                          <el-button class="btn" @click="openMap()" type="primary" plain
                  >设置位置</el-button
                >
              </div>
            </el-form-item>
      <el-form-item label="部门">
        <el-cascader style="width:100%" :props="cascaderProps" v-model="formData.dept_id" :options="deptOptions" clearable>
        </el-cascader>
      </el-form-item>
      <el-form-item label="售后">
        <el-radio-group v-model="formData.dept_type">
          <el-radio :label="key" :key="key" v-for="(item,key) in deeptTypeOption">{{item}}</el-radio>
        </el-radio-group>
        <el-input type="text" placeholder="请输入售后备注" v-model="formData.dept_mark"></el-input>
      </el-form-item>
      <el-form-item label="厂家联系电话">
        <el-input type="text" placeholder="请输入" v-model="formData.factory_phone"></el-input>
      </el-form-item>
      <el-form-item label="设备资料上传">
        <el-upload
                class="upload-demo"
                name="uploadFile"
                :action="baseURL"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleAvatarSuccess"
                multiple
                :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
          <template #tip>
              <div  class="el-upload__tip">支持扩展名：.rar .zip .doc .docx .pdf .jpg...</div>
          </template>

        </el-upload>
      </el-form-item>


    </el-form>
    <el-dialog :close-on-click-modal="false"  title="提示" :destroy-on-close="true" v-model="dialogVisible_map" width="800">
        <div class="setMapBlock-body">
            <div id="rightClickDiv">
                <div class="addProductSpan liHover">选择位置</div>
            </div>
            <div class="setMapBlock" @dbclick="doublelick"  @click="mapClick">
                <img src="@/assets/image/home/map.png" />
                <div class="index-point" style="top:1px;left:1px">
                    <img src="@/assets/image/home/camera.png">
                </div>
            </div>
        </div>
        <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible_map = false">取 消</el-button>
          <el-button type="primary" @click="setIndex()">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <template #footer>
        <el-button @click="dialogVisible_add = false">取 消</el-button>
        <el-button type="primary" @click="confirmAdd">确 定</el-button>
   </template>
  </el-dialog>
</template>

<style  lang="scss" scoped>
  // .xxx-x {
  //   width: 100%;
  //   height: 100%;
  // }
  // 总页面
  .enclosure-box {
    width: 100%;
    height: 100%;
    // background: #141414;
  }
  // 选择
  .enclosure-top{
    padding: 20px;
    background: #141414;
    // border-bottom: 10px solid #d41a1a;
  }
  .enclosure-img img{
    margin: 0 30px 0 5px;
    width: 30px;
    height: 30px;
  }
  .enclosure-img {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .enclosure-bottom {
    padding-top: 10px;
    width: 64%;
    height: calc(100% - 80px);
  }
  .visual-left {
    height: 100%;
    flex: 1;
  
    .camera-hover .hover {
      display: none;
    }
  
    .camera-hover:hover .hover {
      display: block;
    }
  
    .map-block {
      height: 100%;
      // border: 1px solid #318ca2;
      overflow: hidden !important;
      position: relative;
    }
  
    // .map-block img{
    //   width: auto;
    // height: auto;
    // }
  
    .map-id {
      display: inline-block;
      position: absolute;
      cursor: pointer;
  
    }
  
    .map-loading {
      color: #fff;
      position: absolute;
      left: 0;
      width: 100%;
      top: 50%;
      text-align: center;
    }
  
    .map-id .index-point {
      width: 0;
      height: 0;
      position: absolute;
    }
  
    .map-id .index-point img {
      position: absolute;
      width: 100px;
      left: -100px;
      bottom: 0;
    }
  }
  .setMapBlock-body {
    width: 100%;
    height: 500px;
    overflow: hidden !important;
    position: relative;
    border: 1px solid #000;
  }
  .setMapBlock {
    display: inline-block;
    position: absolute;
    cursor: pointer;
  }
  .setMapBlock .index-point {
    width: 0;
    height: 0;
    position: absolute;
    display: none;
  }
  .setMapBlock .index-point img {
    position: absolute;
    width: 144px;
    left: -144px;
    bottom: 0;
  }
  </style>